package cn.itsource.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 我们想要用IOC  你当前的类必须被spring管理否则用不了
 */
@Component
public class EmailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String emailName;

    private static final String TITLE_NAME = "店铺激活邮件";

    public void send1(){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom("382279894@qq.com");
        //邮件主题
        mailMessage.setSubject("上课提醒");
        //邮件内容：普通文件无法解析html标签
        mailMessage.setText("<a href='http://www.baidu.com'>上课不要打瞌睡哟</a>");
        //收件人
        mailMessage.setTo("3109917240@qq.com");
        //发送邮件
        javaMailSender.send(mailMessage);
    }


    public void send2(String msg,String toEmail) {
        try {
            //创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom(emailName);
            helper.setSubject(TITLE_NAME);
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText(msg,true);
            //添加附件
//        helper.addAttachment("p7.jpg",new File("C:\\Users\\Administrator\\Desktop\\1.jpg"));
//        helper.addAttachment("g1.zip", new File("C:\\Users\\Administrator\\Desktop\\1.zip"));
            //收件人
            helper.setTo(toEmail);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
